package com.yuncheng.spcyApi.busService;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.sqsx.SqsxSysxVo;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcyRsJbsx;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.service.ISpcyRsJbsxService;
import com.yuncheng.spcyApi.service.ISpcyRsJjrkService;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Component(value = "flowJobBlsxService")
public class FlowJobBlsxService {

    @Resource
    @Lazy
    private ISpcyRsJjrkService spcyRsJjrkService;

    @Resource
    @Lazy
    private ISpcyRsJbsxService spcyRsJbsxService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    /**
     * 初始化-申请事项-办理时限
     * @return blsx 办理时限
     */
    public void initSqsxBlsxBySqsxId(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        int blsx = 30;
        SqsxSysxVo sqsx = spcySqsxBaiscService.selectSxsxById(sqsxid);
        if (sqsx != null) {
            if (StringUtils.isNotBlank(sqsx.getFsxmc())) {
                List<SpcyRsJbsx> sxList = spcyRsJbsxService.list(new LambdaQueryWrapper<SpcyRsJbsx>()
                        .like(SpcyRsJbsx::getFsxmc, sqsx.getFsxmc()));
                if (CollectionUtils.isNotEmpty(sxList)) {
                    blsx = sxList.get(0).getFbjts();
                }
            }

            LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

            SpcySqsxBasic updateBean = new SpcySqsxBasic();
            updateBean.setFwcsx(blsx);
            updateBean.setFsysx(String.valueOf(blsx));

            spcySqsxBaiscService.update(updateBean, updateWrapper);
        }

    }

    /** 初始化-申请事项-办理时限 */
    public int initSqsxBlsxBySqsxId(SpcySqsxBasic sqsx){
        int blsx = 30;

        if (sqsx == null){
            return blsx;
        }

        if (StringUtils.isNotBlank(sqsx.getFsxmc())) {
            List<SpcyRsJbsx> sxList = spcyRsJbsxService.list(new LambdaQueryWrapper<SpcyRsJbsx>()
                    .like(SpcyRsJbsx::getFsxmc, sqsx.getFsxmc()));
            if (CollectionUtils.isNotEmpty(sxList)) {
                blsx = sxList.get(0).getFbjts();
            }
        }

        return blsx;
    }

    /**
     * 更新申请事项-剩余时限
     * @param sysx 剩余时限
     */
    public void updateSqsxSysx(String sqsxid,String sysx){
        /*SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx != null){
            sqsx.setFsysx(sysx);
            Date jzrq = this.getJzrqBygzrJRq(sqsx.getFjzrq(), sysx);
            if (jzrq != null){
                sqsx.setFjzrq(jzrq);
            }
            spcySqsxBaiscService.updateById(sqsx);
        }*/
        this.updateSqsxSysx(sqsxid,sysx,new BigDecimal("0"));
    }

    /**
     * 更新申请事项-使用时限
     * @param sysx 剩余时限
     * @param sygz 使用工日
     */
    public void updateSqsxSysx(String sqsxid,String sysx, BigDecimal sygz){
//        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        SqsxSysxVo sqsx = spcySqsxBaiscService.selectSxsxById(sqsxid);
        if (sqsx != null){

            SpcySqsxBasic updateBean = new SpcySqsxBasic();

            // 剩余天数
            /*String fsyts = sqsx.getFsysx();
            if (StringUtils.isBlank(fsyts)){
                sysx = "0";
            }else {
                sysx = fsyts;
            }*/
            /*BigDecimal ky = new BigDecimal(sysx);
            BigDecimal sysy = ky.subtract(sygz);
            updateBean.setFsysx(sysy.toString());*/

            // 截止日期
            /*if (sqsx.getFjzrq() != null) {
                Date jzrq = this.getJzrqBygzrJRq(sqsx.getFjzrq(), sysx);
                if (jzrq != null) {
                    sqsx.setFjzrq(jzrq);
                }
            }*/

            // 使用天数
            if (StringUtils.isNotBlank(sygz.toString())){
                String orgSygz = "0";

                if (StringUtils.isNotBlank(sqsx.getFsyts())){
                    orgSygz = sqsx.getFsyts();
                }
                BigDecimal orgDeci = new BigDecimal(orgSygz);
                BigDecimal add = orgDeci.add(sygz);
                updateBean.setFsyts(add.toString());
            }

            LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

            spcySqsxBaiscService.update(updateBean, updateWrapper);
        }
    }

    /**
     * 获取剩余时限-根据申请事项id
     * @return sysx 剩余时限
     */
    public String getSqsxSysx(String sqsxid){
        String sysx = "0";
        SqsxSysxVo sqsx = spcySqsxBaiscService.selectSxsxById(sqsxid);

        /*if (sqsx != null && StringUtils.isNotBlank(sqsx.getFsysx())){
            sysx = sqsx.getFsysx();
        }*/

        if (sqsx == null){
            return sysx;
        }

        try {
            BigDecimal t = new BigDecimal(Optional.ofNullable(sqsx.getFwcsx()).orElse(0));
            BigDecimal sysxBd = t.subtract(new BigDecimal(Optional.ofNullable(sqsx.getFsyts()).orElse("0")));
            return sysxBd.toString();
        }catch (Exception e){
            return sysx;
        }
    }


    /**
     * 各科室-办理环节所需的办理天数
     * @param fywflcode
     * @param currentNode
     * @return
     */
    public String getNodeJzBlts(String fywflcode,String currentNode){
        List<Integer> ypscList = new ArrayList<>();
        List<Integer> ypltList = new ArrayList<>();
        List<Integer> ylqxList = new ArrayList<>();
        ylqxList = Arrays.asList(30,50,4,4,10,4,4,4);
        /**
        ylqxList.add(30); // 任务受理
        ylqxList.add(50); // 方案制作
        ylqxList.add(4); // 查验方案审核
        ylqxList.add(4); // 查验方案审批
        ylqxList.add(10); // 现场检查
        ylqxList.add(4); // 综合评定
        ylqxList.add(4); // 科室复核
        ylqxList.add(4); // 移送
        */

        List<Integer> ypzcList = new ArrayList<>();
        List<Integer> hzpList = new ArrayList<>();

        List<String> nodeList = new ArrayList<>();

        if (StringUtils.isBlank(fywflcode)){
            return "0";
        }
        if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPSC)){
            /*nodeList = Arrays.asList(YpscFlowConstant.NODENAME.split(","));
            for (int i=0 ; i<nodeList.size(); i++){
                if (nodeList.get(0).equals(currentNode)){
                    return ypscList.get(0);
                }
            }*/
            return "0";

        }else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPJY)){
            /*nodeList = Arrays.asList(YpltFlowConstant.NODENAME.split(","));
            for (int i=0 ; i<nodeList.size(); i++){
                if (nodeList.get(0).equals(currentNode)){
                    return ypltList.get(0);
                }
            }*/
            return "0";

        }else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
            /*nodeList = Arrays.asList(YlqxFlowConstant.NODENAME.split(","));
            for (int i=0 ; i<nodeList.size(); i++){
                if (nodeList.get(i).equals(currentNode)){
                    return ylqxList.get(0);
                }
            }*/
            return "0";

        }else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPZC)){
            /*nodeList = Arrays.asList(YpzcFlowConstant.NODENAME.split(","));
            for (int i=0 ; i<nodeList.size(); i++){
                if (nodeList.get(0).equals(currentNode)){
                    return ypzcList.get(0);
                }
            }*/
            return "0";

        }else if (fywflcode.equals(SpcyConstant.YWFL_CODE_HZP)){
            /*nodeList = Arrays.asList(HzpFlowConstant.NODENAME.split(","));
            for (int i=0 ; i<nodeList.size(); i++){
                if (nodeList.get(0).equals(currentNode)){
                    return hzpList.get(0);
                }
            }*/
            return "0";
        }

        return "0";
    }

    /**
     * 工作日加 + 日期 得到 截止日期   (黎-待完善)
     * @param kssj 开始时间
     * @param gzr 工作日（1.1/2.5）
     */
    public Date getJzrqBygzrJRq(Date kssj,String gzr){
        if (kssj == null){
            return kssj;
        }

        if (StringUtils.isBlank(gzr)){
            return kssj;
        }

        if (gzr.contains("-")){
            return kssj;
        }

        int days = 0;
        int hour = 0;

        if (gzr.contains(".")) {
            // 以点分割
            String[] splitStr = gzr.split("\\.");
            days = Integer.valueOf(splitStr[0]); // 天数 （取小数点前的数）
            hour = Integer.valueOf(splitStr[1]); // 小时数 (取小数点后的数)
        }else {
            days = Integer.valueOf(gzr);
        }

        int hours = 0;

        if (hour > 0) {
            BigDecimal hourBig = new BigDecimal(hour * 24);
            BigDecimal tenBig = new BigDecimal(10);
            BigDecimal zshour = hourBig.divide(tenBig, BigDecimal.ROUND_UP);// 向上取整
            hours = Integer.valueOf(zshour.toString());
        }

        // 时间 + 天数
        Date dayTime = null;
        if (days > 0) {
            // 计算行政日期-截止时间
            dayTime = spcyRsJjrkService.getJzsj(kssj, days);
        }else {
            dayTime = kssj;
        }

        // 时间+小时
        Date jzrq = DateConversionUtils.changeDateBaseHour(dayTime, hours);

        return jzrq;
    }

    /**
     * 办结流程-计算工作日
     * @param jssj 接收时间
     * @param bjsj 办结时间
     */
    public String jssygzr(Date jssj, Date bjsj){
        BigDecimal sygzrts = new BigDecimal("0");

        if (jssj == null){
            return sygzrts.toString();
        }

        if (bjsj == null){
            return sygzrts.toString();
        }

        // 对日期进行判断
        Date finaStartDate = spcyRsJjrkService.judgeStart(jssj, bjsj);
        Date finaEndDate = spcyRsJjrkService.judgeEnd(jssj, bjsj);

        sygzrts = spcyRsJjrkService.wxDays(finaStartDate, finaEndDate);

        return sygzrts.toString();
    }

    /**
     * 计算一天八小时制的工作日(培训时间)
     * @param jssj 接收时间
     * @param bjsj 办结时间
     */
    public String jspxsx(Date jssj, Date bjsj){
        BigDecimal sygzrts = new BigDecimal("0");

        if (jssj == null){
            return sygzrts.toString();
        }

        if (bjsj == null){
            return sygzrts.toString();
        }

        // 对日期进行判断
        Date finaStartDate = spcyRsJjrkService.judgeStart(jssj, bjsj);
        Date finaEndDate = spcyRsJjrkService.judgeEnd(jssj, bjsj);

        sygzrts = spcyRsJjrkService.jsPxxs(finaStartDate, finaEndDate);

        return sygzrts.toString();
    }

    /**
     * 计算-当前环节-办理之间的天数  (黎-待完善)
     * @param ksyts 可使用天数
     * @param jssj 接收时间
     * @param bjsj 办结时间
     * @param ztkssj 暂停开始时间
     * @param ztjssj 暂停结束时间
     */
    public String jsTwoDateBetweenDays(String ksyts,String sqsxid,Date jssj, Date bjsj,Date ztkssj,Date ztjssj){
        // 使用工作日
        BigDecimal sygzrts = new BigDecimal("0");

        if (ztkssj == null || ztjssj == null){

            sygzrts = new BigDecimal(this.jssygzr(jssj, bjsj));
//             sygzrts = spcyRsJjrkService.wxDays(jssj, bjsj);

        }else {
            // 暂停开始使用时限
            BigDecimal ztkssysx = new BigDecimal(this.jssygzr(jssj, ztkssj));
//            BigDecimal ztkssysx = spcyRsJjrkService.wxDays(jssj, ztkssj);

            // 暂停结束使用时限
            BigDecimal ztjssysx = new BigDecimal(this.jssygzr(jssj, ztjssj));
//            BigDecimal ztjssysx = spcyRsJjrkService.wxDays(jssj, ztjssj);

            // 暂停开始+暂停结束 = 使用工作日
            sygzrts = ztkssysx.add(ztjssysx);
        }


        // 剩余时限
        BigDecimal ky = new BigDecimal(ksyts);
        BigDecimal sysy = ky.subtract(sygzrts);
        updateSqsxSysx(sqsxid,sysy.toString(),sygzrts); // 更新申请事项-剩余时限

        return sygzrts.toString();
    }

    /**
     * 计算-当前环节-办理所需的天数
     */
    public String jsNodeNeedDays(String fywflcode, String currentNode){
        String days = "0";
        days = this.getNodeJzBlts(fywflcode,currentNode);
        return days;
    }

    /**
     * 计算-流程环节-办理截止日期
     */
    public Date jsNodeJzrq(Date kssj,String gzrts){

        if (gzrts == null || gzrts == "0") {
            return null;
        }else {
            Date jzsj = this.getJzrqBygzrJRq(kssj, gzrts);
            return jzsj;
        }
    }

    /**
     * 判断两个日期-之间是否超时
     * @param syts 使用天数
     * @param cnts 承诺天数
     */
    public String isDateBetweenSfcs(String syts, String cnts){
        String ksts = "0";
        String jsts = "0";

        if (StringUtils.isBlank(syts) || syts.equals("0") || syts.equals("0.0")){
            ksts = "0";

        }else {
            ksts = syts;
        }

        if (StringUtils.isBlank(cnts) || cnts.equals("0") || cnts.equals("0.0")){
            jsts = "0";

        }else {
            jsts = cnts;
        }

//        System.out.println(ksts);
//        System.out.println(jsts);

        BigDecimal sytsBig = new BigDecimal(ksts);
        BigDecimal jstsBig = new BigDecimal(jsts);
        int flag = sytsBig.compareTo(jstsBig); // -1: 小于，0: 等于，1：大于

        String msg = "无时限控制。";

        if (jsts == "0"){
            msg = "无时限控制。";

        }else if (flag < 0){
            msg = "未超时。";

        }else if (flag == 0){
            msg = "最后一天预警。";

        }else if (flag > 0){
            msg = "超时。";

        }

        return msg;
    }

    /**
     * 计算事项库截止日期
     * @param sqsxid 申请事项id
     */
    public Result jsSqsxJzrq(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return Result.error("申请事项id为空");
        }

        SqsxSysxVo basic = spcySqsxBaiscService.selectSxsxById(sqsxid);
        if (basic == null) {
            return Result.error("申请事项数据为空");
        }

        // 受理时间、完成时限,计算截止时间
        if (basic.getFfssj() != null && basic.getFwcsx() != null){
            Date jzsj = spcyRsJjrkService.getJzsj(basic.getFfssj(), basic.getFwcsx());

            LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

            SpcySqsxBasic updateBean = new SpcySqsxBasic();
            updateBean.setFjzrq(jzsj);

            spcySqsxBaiscService.update(updateBean, updateWrapper);
        }

        return Result.ok("计算截止时间完成");
    }

    /** 计算事项库截止日期 */
    public Date jsSqsxJzrq(SpcySqsxBasic basic){
        // 受理时间、完成时限,计算截止时间
        if (basic == null){
            return null;
        }

        if (basic.getFslsj() != null && basic.getFwcsx() != null){
            Date jzsj = spcyRsJjrkService.getJzsj(basic.getFslsj(), basic.getFwcsx());
            return jzsj;
        }

        return null;
    }

}
